package com.lindenvalley.ch;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lindenvalley.ch.application.BerichtApplication;
import com.lindenvalley.ch.content.Task;
import com.lindenvalley.ch.content.User;
import com.lindenvalley.ch.content.Weeks;
import com.lindenvalley.ch.network.OfflineTaskFactory;
import com.lindenvalley.ch.network.WorkServer;
import com.lindenvalley.ch.parser.TaskXmlParser;

public class SignUpActivity extends Activity {
	
	private final String TAG = getClass().getSimpleName();
	private User user;	
	private final WorkServer server = WorkServer.getInstance();
	private static final long millisecondInWeek = 604800000;
	protected static final int ALERT_SIGNUP = 0;
	private Timer timer;
	private NotificationTask task;
	private Calendar cal;
	private int prevDay, prevHour, prevMinutes;
	private ConnectivityManager connectivityManager;
	private NetworkInfo networkInfo;
	private final String USER_FILENAME = "user.ser";
	private BerichtApplication application;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        application = (BerichtApplication)getApplication();
        application.initOfflineTaskId();
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        
        if (timer == null)
        	timer = new Timer();
		
        WorkServer.getInstance().clearData();
        WorkServer.getInstance().destroy();
        setContentView(R.layout.signup);
        TextView tv = (TextView)findViewById(R.id.signupTextView1);
        cal = Calendar.getInstance();
        int weekOfYear = AbstractHomeActivity.getWeekOfYear(cal);
        tv.setText(getString(R.string.actuelleText).concat(String.valueOf(weekOfYear)));
        final Button loginButton = (Button) findViewById(R.id.signupAnmeldenButton);
        Button registerenButton = (Button) findViewById(R.id.signupRegisterenButton);
		final EditText userNameEdit = (EditText) findViewById(R.id.signupRegisterUserName);
		final EditText passwordEdit = (EditText) findViewById(R.id.signupRegisterPassword);
		passwordEdit.setOnKeyListener(new View.OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == MotionEvent.ACTION_UP){
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
					loginButton.performClick();
					return true;
				} else
					return false;
			}
		});

        loginButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				networkInfo = connectivityManager.getActiveNetworkInfo();
				String userNameString = userNameEdit.getText().toString();
				String passwordString = passwordEdit.getText().toString();
				/*
				 * >�AZUBI1_TAGE
					654123
					AZUBI2_WOCHE
					654123
				 */
//				String userNameString = "azubi_tag";
//				String passwordString = "123123";
				try {
					FileInputStream fis = new FileInputStream(getFilesDir() + USER_FILENAME);
					ObjectInputStream inputStream = new ObjectInputStream(fis);
					user = (User) inputStream.readObject();
					inputStream.close();
					fis.close();
					WorkServer.getInstance().setUser(user);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (StreamCorruptedException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				if (userNameString == null || user == null || !user.getUserLogin().equals(userNameString)){
					user = null;
				}
				
				if ((networkInfo != null && networkInfo.isConnected()) || user == null){

					AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>(){
						
						ProgressDialog dialog;
						boolean isCancel = false;
						
						@Override
						protected void onPreExecute (){
							dialog = new ProgressDialog(SignUpActivity.this);
							dialog.setMessage("Connecting....");						
							dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
								
								@Override
								public void onCancel(DialogInterface dialog) {
									isCancel = true;
								}
							});
							dialog.show();
							
						}
	
						@Override
						protected Object doInBackground(Object... params) {
							// TODO Auto-generated method stub
							String[] parameters = (String[]) params[0];
							Object returnValue;
							returnValue =  server.doLogin(parameters[0], parameters[1]);
							if (returnValue instanceof User){
								// Send offline task to server
								OfflineTaskFactory offlineTaskFactory = new OfflineTaskFactory();
								Map<Integer, Task> tasks = offlineTaskFactory.readTaks(SignUpActivity.this);
								if (tasks != null && tasks.size() > 0){
									String action;
									for(Task task: tasks.values()){
										if (task.getTaskId() < 0 ){
											action = WorkServer.TASK_ADD;
										} else{
											action = WorkServer.TASK_UPDATE;
										}
										server.doTask(action, task, user);
									}
									offlineTaskFactory.deleteSerialyzedTask(SignUpActivity.this);
								}
								String result = server.getTasks(((User)returnValue).getUserId(), 2012);
//								Log.i(TAG, result);
								if (!WorkServer.NOT_CONNECT.equals(result)) {
									Serializer serializer = new Persister();
									Weeks weeks = null;
									try {
										weeks = serializer.read(Weeks.class, result);
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
//									TaskXmlParser parser = new TaskXmlParser();
//									Weeks weeks = parser.parse((String)result);
									WorkServer.getInstance().setWeeks(weeks);
								}
							}
							return returnValue;
						}
						
						@Override 
						protected void onPostExecute(Object result) {
					         if (dialog != null && dialog.isShowing()){
					        	 try{
					        		 dialog.dismiss();
					        	 }catch (IllegalArgumentException ex){
					        		 Log.i(TAG, " ----- > Error to close progress dialog wthen device is rotating");
					        	 }
					         }
					        	 
					         if (!isCancel){
						         if (result instanceof String){
										String strValue = (String)result;
										if (WorkServer.NOT_CONNECT.equals(strValue)){
											Toast.makeText(SignUpActivity.this, R.string.NotConnect, Toast.LENGTH_LONG).show();
										} else if (WorkServer.DENY_VALUE.equals(strValue)){
											Toast.makeText(SignUpActivity.this, R.string.InvalidLogin, Toast.LENGTH_LONG).show();
										}
									} else if (result != null){
										Intent intent = null;
										user = (User)result;
										if (User.COMPLETE_WEEK.equals(user.getCompleteTask())){
											intent = new Intent(SignUpActivity.this, WochenberichtActivity.class);
										} else {
											intent = new Intent(SignUpActivity.this, TagesberichtActivity.class);
										}
										try {
											FileOutputStream f = new FileOutputStream(getFilesDir() + USER_FILENAME);
											ObjectOutputStream outputStream = new ObjectOutputStream(f);
											outputStream.writeObject(user);
											outputStream.flush();
											outputStream.close();
											f.close();
										} catch (FileNotFoundException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										
										application.setOffLineWork(false);
										WorkServer.getInstance().setUser(user);
										Weeks weeks = WorkServer.getInstance().getWeeks();
										AbstractHomeActivity.saveWeeks(SignUpActivity.this, weeks);
										startTaskNotification();
										startActivity(intent);
										finish();			        
									} else {
										Toast.makeText(SignUpActivity.this, R.string.NotConnect, Toast.LENGTH_LONG).show();
									}
					         }
					     }
	
						
					};
					String[] params = new String[2];
					params[0] = userNameString;
					params[1] = passwordString;
					Object result = null;
					task.execute(params, null, result);
				} else {
					if (user != null)
						showDialog(ALERT_SIGNUP);
					
				}
				
			}
		});
        
        registerenButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_registeren)));
				startActivity(intent);
			}
        	
        });
	}
		
	
	@Override
	protected void onPause(){
		super.onPause();
		Log.i(TAG,"onPause()");
	}
	
	@Override
	protected void onDestroy(){
		super.onDestroy();
		Log.i(TAG,"onDestroy()");
		
	}
	
	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle(R.string.signAlertTitle);
		dialog.setMessage(R.string.signAlertMessage);
		dialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (user != null){
					Intent intent = null; 
					if (User.COMPLETE_DAY.equals(user.getCompleteTask())){
						intent = new Intent(SignUpActivity.this, TagesberichtActivity.class);
					} else if (user != null){
						intent = new Intent(SignUpActivity.this, WochenberichtActivity.class);
					}
					application.setOffLineWork(true);
					Weeks weeks = AbstractHomeActivity.getWeeks(SignUpActivity.this);
					WorkServer.getInstance().setWeeks(weeks);
					startActivity(intent);
					finish();
				}
			}
		});
		dialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		return dialog.create();
	}


	private void startTaskNotification(){

		long currentTimeInMills = cal.getTimeInMillis();
		if (user.getReminder() == 1){
			if (prevDay != user.getDay() || prevHour != user.getHour() || prevMinutes != user.getMinutes()){
				if (cal.get(Calendar.DAY_OF_WEEK) < user.getDay())
					cal.add(Calendar.DAY_OF_WEEK, user.getDay() - cal.get(Calendar.DAY_OF_WEEK));
				else if (cal.get(Calendar.DAY_OF_WEEK) > user.getDay()){
					cal.add(Calendar.DAY_OF_WEEK, cal.get(Calendar.DAY_OF_WEEK) - (cal.get(Calendar.DAY_OF_WEEK) - user.getDay()));
				}
				
				if (cal.get(Calendar.HOUR_OF_DAY) < user.getHour())
					cal.add(Calendar.HOUR_OF_DAY, user.getHour() - cal.get(Calendar.HOUR_OF_DAY));
				else if (cal.get(Calendar.HOUR_OF_DAY) > user.getHour()){
					cal.roll(Calendar.HOUR_OF_DAY, - (cal.get(Calendar.HOUR_OF_DAY) - user.getHour()));
				}
				
				if (cal.get(Calendar.MINUTE) < user.getMinutes())
					cal.add(Calendar.MINUTE, user.getMinutes() - cal.get(Calendar.MINUTE));
				else if (cal.get(Calendar.MINUTE) > user.getMinutes()){
					cal.roll(Calendar.MINUTE, - (cal.get(Calendar.MINUTE) - user.getMinutes()));
				}
				prevDay = user.getDay();
				prevHour = user.getHour();
				prevMinutes = user.getMinutes();
				if (task != null){
					task.cancel();
				}
				task = new NotificationTask(this);
				Log.i(TAG, "---------" + cal.getTime() + "      " + (cal.getTimeInMillis() - currentTimeInMills));
				timer.schedule(task, cal.getTimeInMillis() - currentTimeInMills, millisecondInWeek);
			}
		} else {
				timer.cancel();
		}

	}

}
